import { _decorator, Component, Vec3, Tween, tween, Node } from 'cc';
import { Battle } from '../Battle';
const { ccclass, property } = _decorator;

@ccclass('ParabolaMovement')
export class ParabolaMovement extends Component {

    public targetNode: Node | null = null; // 目标位置节点
    duration: number = 2; // 动画持续时间（秒）
    height: number = 10; // 抛物线最大高度
    showTrajectory: boolean = true; // 是否显示轨迹

    private _trajectoryNodes: Node[] = []; // 轨迹点数组
    private _startPos: Vec3 = new Vec3();
    private _endPos: Vec3 = new Vec3();

    private moveProgress: number = 0;

    private callback: any;

    // start() {
    //     // this.OnInit();
    //     // this.nodeMoving(this.node);
    // }

    nodeMoving() { //node为做抛物线运动的节点
        let startPos = this.node.getPosition();
        let middlePos = new Vec3(startPos.x, startPos.y, 1) //中间坐标，即抛物线最高点坐标
        let destPos = new Vec3(this.targetNode.position.x, this.targetNode.position.y, 1) //终点，抛物线落地点
        //计算贝塞尔曲线坐标函数
        let twoBezier = (t: number, p1: Vec3, cp: Vec3, p2: Vec3) => {
            let x = (1 - t) * (1 - t) * p1.x + 2 * t * (1 - t) * cp.x + t * t * p2.x;
            let y = (1 - t) * (1 - t) * p1.y + 2 * t * (1 - t) * cp.y + t * t * p2.y;
            return new Vec3(x, y, 0);//xy轴抛物线
        };
        let tweenDuration: number = 0.2;
        let myThis = this;
        tween(this.node.position)
            .to(tweenDuration, destPos, {
                onUpdate: (target: Vec3, ratio: number) => {
                    myThis.node.setPosition(twoBezier(ratio, startPos, middlePos, destPos));
                }
            }).call(() => {
                if (myThis.callback) {
                    myThis.callback();
                }
            }).start();
    }

    OnInit(call) {
        this.callback = call;
        this._startPos = this.node.worldPosition.clone();
        // const playerWorldPos = Battle.playerNode.getWorldPosition();
        const playerWorldPos = this.targetNode.getWorldPosition();
        this._endPos = playerWorldPos.clone();
        this.nodeMoving();
    }

    // 创建轨迹预览
    createTrajectory() {
        // 清除旧轨迹
        this._trajectoryNodes.forEach(node => node.destroy());
        this._trajectoryNodes = [];

        const steps = 20; // 轨迹点数
        for (let i = 0; i <= steps; i++) {
            const progress = i / steps;
            const position = this.calculatePosition(progress);

            const point = new Node('TrajectoryPoint');
            point.setPosition(position);
            this.node.parent?.addChild(point);

            // 添加简单渲染（实际项目中可以使用Sprite或模型）
            point.addComponent('cc.MeshRenderer');

            this._trajectoryNodes.push(point);
        }
    }

    // 计算抛物线位置
    calculatePosition(progress: number): Vec3 {
        const t = progress * this.duration;
        const g = -4 * this.height / Math.pow(this.duration, 2); // 重力加速度

        // 水平方向位移
        const x = this._startPos.x + (this._endPos.x - this._startPos.x) * progress;
        const z = this._startPos.z + (this._endPos.z - this._startPos.z) * progress;

        // 垂直方向位移 (抛物线公式)
        const y = this._startPos.y +
            (this._endPos.y - this._startPos.y) * progress +
            this.height * Math.sin(Math.PI * progress);

        return new Vec3(x, y, z);
    }

    // 播放抛物线动画
    playParabolaAnimation() {
        const start = { progress: 0 };
        const end = { progress: 1 };
        tween(start)
            .to(this.duration, end, {
                onUpdate: (target, ratio) => {
                    this.moveProgress = this.moveProgress + ratio;
                    const position = this.calculatePosition(0.2);
                    this.node.setPosition(position);

                    // // 旋转朝向运动方向（可选）
                    // if (target.progress > 0.01) {
                    //     const prevPosition = this.calculatePosition(target.progress - 0.01);
                    //     const direction = position.clone().subtract(prevPosition).normalize();
                    //     this.node.forward = direction;
                    // }
                },
                easing: 'linear'
            })
            .call(() => {
                console.log('抛物线动画完成');
            })
            .start();
    }
}